package com.lepu.app.fun.grow;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.lepu.app.fun.grow.bean.PhotoItem;
import com.lepu.app.fun.grow.fragment.FragmentGrow;
import com.lepu.app.usercenter.bean.LoginInfo;

/*
 * 保存并同步数据
 */
public class GrowSavePhotoManager implements AsyncRequest {

	private static final String REQUEST_UPLOAD_IMAGE = "request_upload_image";
	private static final String REQUEST_SAVE_UPLOAD_PHOTO = "request_save_upload_photo";

	private static final int MSG_SAVE_PHOTO_SUCCESS = 10;
	private static final int MSG_UPLOAD_IMAGE_ERROR = 20;

	public ArrayList<PhotoItem> mDataList = new ArrayList<PhotoItem>();
	public int mCurrentIndex = 0;

	private static GrowSavePhotoManager mInstance = null;
	private LoginInfo mLoginInfo = MyApplication.getInstance().getLoginInfo();

	public boolean mIsUploading = false;

	private int mCurrentItemId = 0;
	private String mCurrentDateString = "";

	public static GrowSavePhotoManager getInstance() {
		if (mInstance == null) {
			mInstance = new GrowSavePhotoManager();
		}

		return mInstance;
	}

	public void destroy() {
		mInstance = null;

		mIsUploading = false;
		LogUtilBase.LogD(null, "取消云端同步上传图片");
	}

	public void init(String dateString) {

		mCurrentDateString = dateString;
		String uid = mLoginInfo.UserID;
		mDataList = PhotoItem.getPhotosByDateNoUpdate(uid, dateString);

		if (mDataList != null) {
			LogUtilBase
					.LogD(null, String.format("需要上传%d张图片", mDataList.size()));
		}
	}

	public void uploadImageContent() {

		if (mInstance == null) {
			return;
		}

		if (mDataList == null || mDataList.size() == 0) {
			LogUtilBase.LogD(null, "未初始化数据，或者没有可上传数据");

			UIHelper.showToast(MyApplication.getInstance(), "没有可同步的照片");
			destroy();
			return;
		}

		mIsUploading = true;

		if (mCurrentIndex <= mDataList.size() - 1) {
			PhotoItem item = mDataList.get(mCurrentIndex);

			mCurrentItemId = item.id;

			Map<String, File> fileMap = new HashMap<String, File>();
			fileMap.put("Photo", new File(item.imagePath));

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();
			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);

				params.put("UserID", mLoginInfo.UserID);
				params.put("LoginToken", mLoginInfo.LoginToken);

				if (item.modifyState == PhotoItem.MODIFY_YES) {
					params.put("PhotoID", item.pictureId);// 修改
				}

				params.put("TakePictureDate", item.addTime);
				params.put("NativePhotoID", item.id);
				params.put("Description", item.desc);
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put("ht", params);

			String url = Setting.getAddPhotoUrl();
			if (item.modifyState == PhotoItem.MODIFY_YES) {
				url = Setting.getModifyPhotoUrl();// 修改
			}

			ApiClient.http_post(url, map, fileMap, this, REQUEST_UPLOAD_IMAGE,
					false);
		}

		requestSaveUploadPhoto();
	}

	private void requestSaveUploadPhoto() {
		if (mInstance == null) {
			return;
		}

		if (mDataList == null || mDataList.size() == 0) {
			LogUtilBase.LogD(null, "未初始化数据，或者没有可上传数据");
			return;
		}

		// 说明上传完图片了，需要保存同步接口
		if (mCurrentIndex > mDataList.size() - 1) {

			ArrayList<PhotoItem> dataList = PhotoItem.getPhotosByDate(
					mLoginInfo.UserID, mCurrentDateString);
			String result = "";
			if (dataList != null && dataList.size() > 0) {
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < dataList.size(); i++) {
					sb.append(dataList.get(i).pictureId);
					sb.append("|");
				}
				sb.deleteCharAt(sb.length() - 1);

				result = sb.toString();

				Map<String, Object> map = new HashMap<String, Object>();
				JSONObject params = new JSONObject();
				try {
					params.put("DeviceID", Setting.DEVICEID);
					params.put("ApplicationID", Setting.APPLICATIONID);
					params.put("UserID", mLoginInfo.UserID);
					params.put("LoginToken", mLoginInfo.LoginToken);

					params.put("SyncTime", mCurrentDateString);
					params.put("PhotoIDs", result);
				} catch (Exception e) {
					e.printStackTrace();
				}
				map.put("ht", params);

				ApiClient.http_post(Setting.getSyncToCloudUrl(), map, null,
						this, REQUEST_SAVE_UPLOAD_PHOTO, false);
			}
		}
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_SAVE_PHOTO_SUCCESS:

				UIHelper.showToast(MyApplication.getInstance(), "保存同步成功");
				
				FragmentGrow.getInstance().showUploadSuccessDialog();
				break;
			case MSG_UPLOAD_IMAGE_ERROR:

				UIHelper.showToast(MyApplication.getInstance(),
						"上传图片失败，请检查网络，重新上传..");
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {

		if (object.equals(REQUEST_UPLOAD_IMAGE)) {
			boolean flag = false;
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");

				int PhotoID = obj2.optInt("PhotoID");// 服务器返回需要保存的id
				// int NativePhotoID = obj2.optInt("NativePhotoID");//
				// 本地数据库唯一id对应
				// String PhotoUrl = obj2.optString("PhotoUrl");

				flag = PhotoItem.updatePhotoItemSyncById(mLoginInfo.UserID,
						mCurrentItemId, PhotoID);

			} catch (JSONException e) {
				e.printStackTrace();
			}

			LogUtilBase.LogD(null, String.format(
					"RequestComplete 第%d张图片上传结果==%s", mCurrentIndex,
					String.valueOf(flag)));

			mCurrentIndex++;

			Message msg = new Message();
			msg.arg1 = mCurrentIndex;
			msg.arg2 = mDataList.size();
			msg.what = FragmentGrow.MSG_UPLOAD_DATA;
			FragmentGrow.getInstance().mHandler.sendMessage(msg);

			uploadImageContent();
		} else if (object.equals(REQUEST_SAVE_UPLOAD_PHOTO)) {

			boolean flag = false;
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");

				int HotAlbumID = obj2.optInt("HotAlbumID");// 服务器返回需要保存的id
				LogUtilBase.LogD(null,
						"HotAlbumID==" + String.valueOf(HotAlbumID));
				flag = true;

			} catch (JSONException e) {
				e.printStackTrace();
			}

			mHandler.sendEmptyMessage(MSG_SAVE_PHOTO_SUCCESS);

			FragmentGrow.getInstance().mHandler
					.sendEmptyMessage(FragmentGrow.MSG_SAVE_UPLOAD_SUCCESS);

			LogUtilBase.LogD(null, "REQUEST_APPLY_HOT_PHOTO==" + flag);
			destroy();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_UPLOAD_IMAGE)) {
			LogUtilBase.LogD(null, "上传图片失败    " + mCurrentIndex);

			// mCurrentIndex ++;
			// uploadImageContent();

			mHandler.sendEmptyMessage(MSG_UPLOAD_IMAGE_ERROR);
			destroy();
		} else if (object.equals(REQUEST_SAVE_UPLOAD_PHOTO)) {

			FragmentGrow.getInstance().mHandler
					.sendEmptyMessage(FragmentGrow.MSG_SAVE_UPLOAD_SUCCESS);

			destroy();
			LogUtilBase.LogD(null, "REQUEST_APPLY_HOT_PHOTO==error");
		}

	}

}